import { createBrowserRouter, matchRoutes, Navigate, type RouteObject } from "react-router-dom";
import { lazy } from "react";
import AuthRoute from "./AuthRoute";
import { deepCloneOverall } from "@/utils/tool";
const Error = lazy(() => import("@/pages/error"));
const Layouts = lazy(() => import("@/layouts/Index"));
const Login = lazy(() => import("@/pages/login/Index"));

export const defRoutes: RouteObject[] = [
  {
    path: "/",
    element: <AuthRoute />,
    children: [
      {
        path: "/",
        element: <Layouts />,
        children: [
          {
            index: true,
            element: <Navigate to="/home" />, // 自动重定向到 /home
          },
        ],
      },
      {
        path: "/login",
        element: <Login />,
        handle: {
          meta: { title: "登录页面" },
        },
      },
      {
        path: "/error",
        element: <Error />,
        handle: {
          meta: { title: "错误页面" },
        },
      },
      {
        path: "*",
        element: <Error />,
        handle: {
          meta: { title: "错误页面" },
        },
      },
    ],
  },
];

// 新增：维护一个订阅者列表
let listeners: ((router: any) => void)[] = [];

// 新增：外部注册回调
export function onRouterChange(cb: (router: any) => void) {
  listeners.push(cb);
}

let routes: RouteObject[] = deepCloneOverall(defRoutes);

let router = createBrowserRouter(routes);

/** 获取最新的路由对象 */
export function getRouter() {
  return router;
}

// 动态添加路由
export function addRoute(route: RouteObject) {
  let oldRoutes = (routes.find((item) => item.path === "/") as RouteObject).children?.find(
    (item) => item.path === "/"
  ) as RouteObject;
  oldRoutes.children = [...(oldRoutes.children as RouteObject[]), route];
  router = createBrowserRouter(routes); // 重新生成
  listeners.forEach((cb) => cb(router)); // 通知所有监听者
  return router;
}

/** 获取最新的路由配置 */
export function getRoutes() {
  return routes;
}

/**
 * 获取路由配置
 * @param pathname path地址
 * @returns router信息
 */
export function getMatches(pathname: string) {
  // 第二个参数是你要匹配的 pathname（window.location.pathname 或手动传入）
  return matchRoutes(routes as RouteObject[], pathname);
}
